package cn.itcast.bos.web.action;

import java.util.concurrent.TimeUnit;

import javax.annotation.Resource;
import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.Message;
import javax.jms.Session;
import javax.ws.rs.core.MediaType;

import org.apache.commons.lang.math.RandomUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.cxf.jaxrs.client.WebClient;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Controller;

import cn.itcast.bos.constant.Constants;
import cn.itcast.bos.utils.MailUtils;
import cn.itcast.crm.domain.Customer;

@Controller
@Namespace("/")
@ParentPackage("json-default")
@Scope("prototype")
public class CustomerAction extends BaseAction<Customer> {

	@Action(value = "customer_login", results = {
			@Result(name = "success", location = "index.html#/myhome", type = "redirect"),
			@Result(name = "login", location = "login.html", type = "redirect") })
	public String login() {

		Customer customer = WebClient
				.create(Constants.CRM_MANAGEMENT_URL + "/services/customerService/customer/login?telephone="
						+ model.getTelephone() + "&password=" + model.getPassword())
				.accept(MediaType.APPLICATION_JSON).get(Customer.class);

		if(customer==null) {
			return LOGIN;
		}else {
			ServletActionContext.getRequest().getSession().setAttribute("customer", customer);
			return SUCCESS;
		}
		
	}

	/**
	 * 发送验证码并接受验证码
	 * 
	 * @return
	 * @throws Exception
	 */
	@Resource(name = "jmsQueueTemplate")
	private JmsTemplate jmsTemplate;

	@Action(value = "customer_sendSms")
	public String sendSms() throws Exception {
		/*
		 * 网易云短信 // String resp = SendCode.sendSms(model.getTelephone()); //
		 * 假的请求 String resp = "{'code':200,'msg':'3','obj':'521521'}"; String[]
		 * split = resp.split(","); String code = split[0].substring(8); String
		 * msg = split[1].substring(7, split[1].length() - 1); String randomCode
		 * = split[2].substring(7, split[2].length() - 2);
		 */

		String randomCode = RandomStringUtils.randomNumeric(4);
		// 将短信验证码保存到session

		ServletActionContext.getRequest().getSession().setAttribute(model.getTelephone(), randomCode);
		System.out.println("生成的验证码为：" + randomCode);

		final String msg = "您的验证码为：" + randomCode;

		jmsTemplate.send("bos_sms", new MessageCreator() {

			@Override
			public Message createMessage(Session session) throws JMSException {
				MapMessage mapMessage = session.createMapMessage();
				mapMessage.setString("telephone", model.getTelephone());
				mapMessage.setString("msg", msg);
				return mapMessage;
			}
		});
		return NONE;

		/*
		 * if (code.equals("200")) { // 发送成功 return NONE; } else { throw new
		 * RuntimeException("短信发送失败，信息码：" + code); }
		 */

	}

	/**
	 * 用户注册
	 */
	private String checkcode;

	public void setCheckcode(String checkcode) {
		this.checkcode = checkcode;
	}

	@Autowired
	private RedisTemplate<String, String> redisTemplate;

	@Action(value = "customer_regist", results = {
			@Result(name = "success", type = "redirect", location = "signup-success.html"),
			@Result(name = "input", type = "redirect", location = "signup.html") })
	public String regist() {
		System.out.println(model);
		// 先校验短信验证码，如果不通过，调回注册页面
		// 从session获取之前生成的验证码
		System.out.println(
				"存储在session中的验证码：" + ServletActionContext.getRequest().getSession().getAttribute(model.getTelephone()));

		String checkcodeSession = (String) ServletActionContext.getRequest().getSession()
				.getAttribute(model.getTelephone());
		if (checkcodeSession == null || !checkcodeSession.equals(checkcode)) {
			System.out.println("短信验证码错误...");
			return INPUT;
		}
		WebClient.create("http://localhost:9002/crm_management/services/customerService/customerregist")
				.type(MediaType.APPLICATION_JSON).post(model);
		System.out.println("客户注册成功...");

		// 发送激活邮件
		String activecode = RandomStringUtils.randomNumeric(32);
		redisTemplate.opsForValue().set(model.getTelephone(), activecode, 24, TimeUnit.HOURS);
		String content = "教学用地址：<br/><a href='" + MailUtils.activeUrl + "?telephone=" + model.getTelephone()
				+ "&activecode=" + activecode + "'>教学用激活地址</a>" + MailUtils.activeUrl + "?telephone="
				+ model.getTelephone() + "&activecode=" + activecode;
		MailUtils.sendMail("收到激活邮件", content, model.getEmail());

		return SUCCESS;
	}

	// 激活账号

	private String activecode;

	public void setActivecode(String activecode) {
		this.activecode = activecode;
	}

	@Action(value = "customer_activeMail")
	public String activeMail() throws Exception {
		ServletActionContext.getResponse().setContentType("text/html;charset=utf-8");
		// 判断激活码是否有效
		String activecodeRedis = redisTemplate.opsForValue().get(model.getTelephone());
		if (activecodeRedis == null || !activecodeRedis.equals(activecode)) {
			ServletActionContext.getResponse().getWriter().println("激活码无效，请登录系统，重新绑定邮箱！");
		} else {
			/**
			 * 激活码有效 防止重复绑定 调用CRM webService查询客户信息，判断是否已经绑定
			 */
			Customer customer = WebClient
					.create("http://localhost:9002/crm_management/services/customerService/customer/telephone/"
							+ model.getTelephone())
					.accept(MediaType.APPLICATION_JSON).get(Customer.class);
			if (customer.getType() == null || customer.getType() != 1) {
				// 没有绑定
				WebClient.create("http://localhost:9002/crm_management/services/customerService/customer/updatetype/"
						+ model.getTelephone()).get();
				ServletActionContext.getResponse().getWriter().println("邮箱绑定成功！");
			} else {
				// 已经绑定过
				ServletActionContext.getResponse().getWriter().println("邮箱已经绑定过，无需重复绑定！");
			}
			redisTemplate.delete(model.getTelephone());
		}
		return NONE;
	}
}
